package org.yoyo.classroom.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.yoyo.classroom.domain.po.Permission;
import org.yoyo.classroom.result.Result;
import org.yoyo.classroom.service.PermissionService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @GetMapping("/permissions")
    public Result<List<Permission>> getAllPermissions() {
        List<Permission> permissions = permissionService.getAllPermissions();
        if (permissions != null) {
            return Result.success(permissions);
        } else {
            return Result.error("Failed to get permissions");
        }
    }

    @GetMapping("/permissions/{id}")
    public Result<Permission> getPermissionById(@PathVariable Long id) {
        Permission permission = permissionService.getPermissionById(id);
        if (permission != null) {
            return Result.success(permission);
        } else {
            return Result.error("Permission not found");
        }
    }

    @PostMapping("/permissions")
    public Result<String> addPermission(@RequestBody Permission permission) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        permission.setCreateTime(dateFormat.format(new Date()));
        permission.setIsDeleted(0);
        boolean isAdded = permissionService.addPermission(permission);
        if (isAdded) {
            return Result.success("Permission added successfully");
        } else {
            return Result.error("Failed to add permission");
        }

    }

    @PutMapping("/permissions/{id}")
    public Result<String> updatePermission(@PathVariable Long id, @RequestBody Permission permission) {
        permission.setId(id);
        boolean isUpdated = permissionService.updatePermission(permission);
        if (isUpdated) {
            return Result.success("Permission updated successfully");
        } else {
            return Result.error("Failed to update permission");
        }
    }

    @DeleteMapping("/permissions/{id}")
    public Result<String> deletePermission(@PathVariable Long id) {
        boolean isDeleted = permissionService.deletePermission(id);
        if (isDeleted) {
            return Result.success("Permission deleted successfully");
        } else {
            return Result.error("Failed to delete permission");
        }
    }

    @GetMapping("/findPersission/{roleId}")
    public Result findPermissionByRoleId(@PathVariable("roleId") Integer roleId) {
        List<Permission> findPermissionByRoleIdList = permissionService.findPermissionByRoleId(roleId);
        Result result = new Result();
        result.setData(findPermissionByRoleIdList);
        result.setCode(200);
        return result;
    }
}
